const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, QueryTypes} = require("../../models/db");
const tools = require("../../tools/tool");
// 供应商对账单
router.post('/list/getBillpromx', async ctx => {
    try {
        let user = ctx.user
        let body = ctx.request.body
        let tenantId = user.tenantId;
        let buId = body.formData.buId;
        let beg = body.formData.beginDate ? body.formData.beginDate : '2001-01-01';
        let end = body.formData.endDate ? body.formData.endDate : tools.getDay()
        if(!buId) return ctx.err('请选择供应商')
        let initSql = `
            select  sum(jy) jy
                   from v_invoice_dz_yf
                   where tenantId = ${tenantId}
                     and buId = ${buId}
                     and billDate < '${beg}' and billType<>'YF2YF'
            group by buId 
        `
        let initRet = await db.query(initSql, {type: QueryTypes.SELECT, plain: true})
        let initRow = {
            transTypeName: '期初',
            jy: ''
        }
        if(initRet) {
            initRow.jy = initRet.jy
        }
        let listSql = `
                    select id, buId, billNo, billDate, transTypeName, totalAmount, disAmount, rpAmount,
                           ys,jy,skYh,
                           billType,
                           hxAmount,hxAt 
                    from v_invoice_dz_yf
                    where tenantId = ${tenantId}
                      and buId = ${buId}
                      and billDate >= '${beg}' and billDate<='${end}' and billType<>'YF2YF' 
                    order by billDate,id
        `
        let list = await db.query(listSql, {type: QueryTypes.SELECT})

        list.unshift(initRow)
        for (let i = 0; i < list.length; i++) {
            if(i === 0) continue
            let row = list[i]
            row.jy = tool.add(list[i-1].jy,row.jy)
            let hxLeft = tool.minus(tool.minus(row.ys, row.rpAmount), row.hxAmount)
            if(hxLeft === 0) {
                row.hxStat = '核销完'
            }
            if(hxLeft !== 0) {
                if(tool.xe.toNumber(row.hxAmount) !== 0) {
                    row.hxStat = '部分核销'
                }
                else {
                    row.hxStat = ''
                }
            }
        }
        return ctx.suc('', {
            total: 0,
            list: list
        })
    } catch (e) {
        return ctx.err(e);
    }
})

module.exports = router;